<template>
  <li :class="activeCls" @click="handleClick">
    <i :class="iconCls"></i>
    <span><slot></slot></span>
  </li>
</template>

<script>
export default {
  name: 'MenuItem',
  props: {
    name: {
      type: String,
      required: true
    },
    icon: {
      type: String,
      default: () => ''
    },
    to: {
      type: String,
      default: () => ''
    }
  },
  inject: ['itemObj'],
  data() {
    return {}
  },
  methods: {
    handleClick() {
      this.itemObj.name = this.name
      // 选中效果处理，只支持二级菜单，还需要扩展优化
      // const allItems = []
      // if (this.$parent.$options.name === 'SubMenu') {
      //   const arr = this.$parent.$parent.$children
      //   arr.forEach(item => {
      //     if (item.$children.length) {
      //       item.$children.forEach(items => {
      //         allItems.push(items)
      //       })
      //     } else {
      //       allItems.push(item)
      //     }
      //   })
      // }
      // if (this.$parent.$options.name === 'Menu') {
      //   const arr = this.$parent.$children
      //   arr.forEach(item => {
      //     if (item.$children.length) {
      //       item.$children.forEach(items => {
      //         allItems.push(items)
      //       })
      //     } else {
      //       allItems.push(item)
      //     }
      //   })
      // }
      // allItems.filter(item => item.name === this.name)[0].isActive = true
      // allItems.filter(item => item.name !== this.name).forEach(item => (item.isActive = false))

      // 路由跳转
      this.$router.push(this.to)
    }
  },
  mounted() {
    if (this.$parent.$options.name === 'SubMenu') {
      this.itemObj.name = this.$parent.$parent.value
    }
    if (this.$parent.$options.name === 'Menu') {
      this.itemObj.name = this.$parent.value
    }
  },
  computed: {
    iconCls: function() {
      return [
        'iconfont',
        {
          [`icon-${this.icon}`]: this.icon !== ''
        }
      ]
    },
    activeCls: function() {
      return ['menu-item', { active: this.itemObj.name === this.name }]
    }
  }
}
</script>
